package data;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class Comm {
	private CommPortIdentifier portId;
	private Vector<Serializable> data;
	
	public Comm() {
		portId = null;
		data = new Vector<Serializable>();
	}
	
	public Comm(CommPortIdentifier portId, Serializable[] data) {
		this.portId = portId;
		this.data = new Vector<Serializable>();
		for (Serializable s: data) this.data.add(s);
	}
	
	public CommPortIdentifier getPortId() {
		return portId;
	}
	
	/*public Serializable getData() {
		return data;
	}*/
	
	public void setPortId(CommPortIdentifier portId) {
		this.portId = portId;
	}
	
	public void addData(Serializable data) {
		this.data.add(data);
	}
	
	public void send() throws PortInUseException {
		SerialPort port = (SerialPort) portId.open("MIDIFX", 2000);
		try { // 31250 not supported on FTDI windows driver (hacked driver)
			port.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
			OutputStream os = port.getOutputStream();
			try {
				Thread.sleep(1500);
				os.write(0xF0);
				os.write(0x7F);
				for (Serializable s: data) {
					s.serialize(os);
					System.out.println(s.toString());
					System.out.println("");
				}
				os.write(0xF7);
			} 
			catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			port.close();
			/*InputStream is = port.getInputStream();
			while (true) {
				while (is.available() > 0) {
					System.out.println("" + is.read());
				}
			}*/
		} 
		catch (IOException ioe) {
			ioe.printStackTrace();
		} 
		catch (UnsupportedCommOperationException ucoe) {
			ucoe.printStackTrace();
		}
	}
}